
import express from 'express';
import cors from 'cors';
import helmet from 'helmet';
import compression from 'compression';
import morgan from 'morgan';
import rateLimit from 'express-rate-limit';
import bcrypt from 'bcryptjs';

// 导入统一数据库
import unifiedDB from './database-unified.js';

const app = express();
const PORT = process.env.BACKEND_PORT || 3000;

// 中间件配置
app.use(helmet());
app.use(compression());
app.use(morgan('combined'));
app.use(cors({
  origin: process.env.ALLOWED_ORIGINS ? process.env.ALLOWED_ORIGINS.split(',') : ['http://localhost:8080'],
  credentials: true
}));
app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ extended: true }));

// 速率限制
const apiLimiter = rateLimit({
  windowMs: parseInt(process.env.RATE_LIMIT_WINDOW_MS) || 900000,
  max: parseInt(process.env.RATE_LIMIT_MAX_REQUESTS) || 100,
  message: '请求过于频繁，请稍后再试'
});
app.use('/api/', apiLimiter);

// 全局数据库连接状态
let dbConnected = false;

// 初始化数据库连接
async function initializeDatabase() {
  try {
    console.log('🔗 初始化数据库连接...');
    await unifiedDB.connect();
    await unifiedDB.initialize();
    
    // 测试连接
    const testResult = await unifiedDB.testConnection();
    if (testResult) {
      dbConnected = true;
      console.log('✅ 数据库连接初始化成功');
      
      // 插入示例数据
      await insertSampleData();
    } else {
      console.warn('⚠️ 数据库连接测试失败，但服务将继续运行');
    }
  } catch (error) {
    console.error('❌ 数据库初始化失败:', error.message);
    console.log('💡 服务将以无数据库模式运行');
  }
}

// 插入示例数据
async function insertSampleData() {
  try {
    // 检查是否已有数据
    const userCount = await unifiedDB.query('SELECT COUNT(*) as count FROM users');
    
    if (userCount.rows[0].count === 0) {
      console.log('📊 插入示例数据...');
      
      // 插入管理员用户 - 使用环境变量
      const adminPassword = process.env.ADMIN_PASSWORD || 'admin123';
      const hashedPassword = await bcrypt.hash(adminPassword, 12);
      await unifiedDB.query(
        'INSERT INTO users (username, email, password, role) VALUES (?, ?, ?, ?)',
        ['admin', 'admin@example.com', hashedPassword, 'admin']
      );
      
      // 插入普通用户
      const userPassword = await bcrypt.hash('user123', 10);
      await unifiedDB.query(
        'INSERT INTO users (username, email, password) VALUES (?, ?, ?)',
        ['user1', 'user1@example.com', userPassword]
      );
      
      // 插入示例产品
      const products = [
        ['山地自行车', '专业级山地自行车，适合越野骑行', 2999.99, '山地车', 10],
        ['公路自行车', '轻量化公路自行车，适合长途骑行', 1999.99, '公路车', 15],
        ['城市通勤车', '舒适的城市通勤自行车', 899.99, '城市车', 20],
        ['儿童自行车', '安全可靠的儿童自行车', 499.99, '儿童车', 8]
      ];
      
      for (const product of products) {
        await unifiedDB.query(
          'INSERT INTO products (name, description, price, category, stock) VALUES (?, ?, ?, ?, ?)',
          product
        );
      }
      
      console.log('✅ 示例数据插入完成');
    }
  } catch (error) {
    console.warn('⚠️ 插入示例数据失败:', error.message);
  }
}

// 健康检查端点
app.get('/health', async (req, res) => {
  const healthStatus = {
    status: dbConnected ? 'healthy' : 'degraded',
    timestamp: new Date().toISOString(),
    version: '1.0.0',
    database: {
      connected: dbConnected,
      type: unifiedDB.dbType,
      fallback: unifiedDB.fallbackEnabled
    },
    services: {
      api: 'running',
      database: dbConnected ? 'connected' : 'disconnected'
    }
  };
  
  res.json(healthStatus);
});

// 用户认证相关API
app.post('/api/auth/login', async (req, res) => {
  try {
    const { email, password } = req.body;
    
    if (!email || !password) {
      return res.status(400).json({
        success: false,
        message: '邮箱和密码不能为空'
      });
    }
    
    if (!dbConnected) {
      return res.status(503).json({
        success: false,
        message: '数据库服务不可用'
      });
    }
    
    // 查询用户
    const userResult = await unifiedDB.query(
      'SELECT * FROM users WHERE email = ?',
      [email]
    );
    
    if (userResult.rows.length === 0) {
      return res.status(401).json({
        success: false,
        message: '用户不存在'
      });
    }
    
    const user = userResult.rows[0];
    
    // 验证密码
    const isValidPassword = await bcrypt.compare(password, user.password);
    if (!isValidPassword) {
      return res.status(401).json({
        success: false,
        message: '密码错误'
      });
    }
    
    // 登录成功（简化版，不包含JWT）
    res.json({
      success: true,
      message: '登录成功',
      user: {
        id: user.id,
        username: user.username,
        email: user.email,
        role: user.role
      }
    });
    
  } catch (error) {
    console.error('登录错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
});

// 产品API
app.get('/api/products', async (req, res) => {
  try {
    if (!dbConnected) {
      return res.json({
        success: true,
        data: [],
        message: '数据库不可用，返回空数据'
      });
    }
    
    const products = await unifiedDB.query('SELECT * FROM products');
    
    res.json({
      success: true,
      data: products.rows,
      total: products.rows.length
    });
    
  } catch (error) {
    console.error('获取产品列表错误:', error);
    res.status(500).json({
      success: false,
      message: '获取产品列表失败'
    });
  }
});

// 用户API
app.get('/api/users', async (req, res) => {
  try {
    if (!dbConnected) {
      return res.json({
        success: true,
        data: [],
        message: '数据库不可用，返回空数据'
      });
    }
    
    const users = await unifiedDB.query('SELECT id, username, email, role, created_at FROM users');
    
    res.json({
      success: true,
      data: users.rows,
      total: users.rows.length
    });
    
  } catch (error) {
    console.error('获取用户列表错误:', error);
    res.status(500).json({
      success: false,
      message: '获取用户列表失败'
    });
  }
});

// 仪表板数据API
app.get('/api/dashboard', async (req, res) => {
  try {
    let stats = {
      totalUsers: 0,
      totalProducts: 0,
      totalOrders: 0,
      revenue: 0
    };
    
    if (dbConnected) {
      try {
        const usersResult = await unifiedDB.query('SELECT COUNT(*) as count FROM users');
        const productsResult = await unifiedDB.query('SELECT COUNT(*) as count FROM products');
        
        stats.totalUsers = usersResult.rows[0].count;
        stats.totalProducts = productsResult.rows[0].count;
      } catch (dbError) {
        console.warn('获取仪表板数据失败:', dbError.message);
      }
    }
    
    res.json({
      success: true,
      data: stats
    });
    
  } catch (error) {
    console.error('获取仪表板数据错误:', error);
    res.status(500).json({
      success: false,
      message: '获取仪表板数据失败'
    });
  }
});

// 404处理
app.use('*', (req, res) => {
  res.status(404).json({
    success: false,
    message: '接口不存在'
  });
});

// 错误处理中间件
app.use((error, req, res, next) => {
  console.error('服务器错误:', error);
  res.status(500).json({
    success: false,
    message: process.env.NODE_ENV === 'production' ? '服务器内部错误' : error.message
  });
});

// 启动服务器
async function startServer() {
  try {
    console.log('🔧 启动统一数据库后端服务器...');
    
    // 初始化数据库（不阻塞服务器启动）
    initializeDatabase().then(() => {
      console.log('✅ 数据库初始化完成');
    }).catch(error => {
      console.warn('⚠️ 数据库初始化失败，但服务将继续运行:', error.message);
    });
    
    // 启动HTTP服务器
    const server = app.listen(PORT, () => {
      console.log(`🚀 统一数据库后端服务器运行在 http://localhost:${PORT}`);
      console.log(`📊 健康检查: http://localhost:${PORT}/health`);
      console.log(`🔗 API文档: http://localhost:${PORT}/api`);
      console.log('💡 数据库类型:', dbConnected ? unifiedDB.dbType : '无数据库连接');
    });
    
    // 优雅关闭
    process.on('SIGTERM', async () => {
      console.log('收到SIGTERM信号，正在关闭服务器...');
      await unifiedDB.close();
      server.close(() => {
        process.exit(0);
      });
    });
    
    process.on('SIGINT', async () => {
      console.log('收到SIGINT信号，正在关闭服务器...');
      await unifiedDB.close();
      server.close(() => {
        process.exit(0);
      });
    });
    
    return server;
  } catch (error) {
    console.error('❌ 服务器启动失败:', error);
    process.exit(1);
  }
}

export default app;

// 启动服务器
if (import.meta.url === `file://${process.argv[1]}`) {
  startServer().catch(error => {
    console.error('❌ 服务器启动失败:', error);
    process.exit(1);
  });
}